<template>
  <div class="app-container editManage" style="padding: 0">
    <el-form>
      <el-form-item
        label="配送区域及运费"
        prop="areaFreight"
        name="areaFreight"
        class="areaFreight"
      >
        <!-- 按重量 -->
        <el-table
          :data="tableData.tableBodyList"
          style="width: 100%"
          :header-cell-style="{ textAlign: 'center' }"
          :cell-style="{ textAlign: 'center' }"
        >
          <el-table-column
            v-for="(item, index) in tableData.tableHeaderList"
            :key="item.index"
            :prop="item.prop"
            :label="item.label"
            :showMethod="item.showMethod"
            align="center"
          >
            <template slot-scope="scope">
              <div style="display: flex; gap: 10px">
                <el-input-number
                  :min="0"
                  v-if="item.showMethod === 'number'"
                  v-model="scope.row[scope.column.property]"
                  controls-position="right"
                ></el-input-number>
                <div v-else>
                  <el-cascader
                    v-model="scope.row[scope.column.property]"
                    :ref="'cascader'"
                    :options="addressList"
                    collapse-tags
                    :props="{
                      multiple: true,
                      label: 'name',
                      children: 'children',
                      value: 'code',
                    }"
                    clearable
                  ></el-cascader>
                </div>
                <el-button
                  v-if="scope.column.property == 'picCanArea'"
                  type="text"
                  @click="remoteItem(scope)"
                  >删除</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addAddress"
          >添加可配送区域和运费</el-button
        >
      </el-form-item>
    </el-form>

    ​
    <!-- 添加可配送区域及运费弹出框 -->
    ​
    <!--  <el-dialog title="选择地区" :visible.sync="dialogVisible">

      <div class="areaCheckBox">
        <div class="province">


         <el-checkbox :indeterminate="isIndeterminate" @change="handleCheckAllChange"
           custom-class="import-dialog">全选</el-checkbox>

          <div style="margin: 15px 0;"></div>

         <el-tree :data="address.province" show-checkbox default-expand-all node-key="code" ref="tree" highlight-current
           :props="{label:'name',children:''}">
         </el-tree>
       </div>

        <div class="city">
          <div style="margin-bottom: 15px;font-size:12px;color:#ccc;text-align:center">请选择市</div>


         <el-tree :data="address.city" @node-click="handleCheckedCityChange" @check-change="" show-checkbox default-expand-all node-key="code" ref="tree" highlight-current
           :props="{label:'name',children:''}">
         </el-tree>
       </div>

        <div class="country">
          <div style="color:#ccc;margin-bottom: 15px;font-size:12px;">请选择区/县</div>


         <el-tree :data="address.area" show-checkbox default-expand-all node-key="code" ref="tree" highlight-current
           :props="{label:'name',children:''}">
         </el-tree>
       </div>
     </div>
     <el-button @click="dialogVisible = false">取 消</el-button>
     <el-button type="primary" @click="handleArea">确 定</el-button>

   </el-dialog> -->
  </div>
</template>

<script>
// 接口api：first step
import { getNotice, addNotice, updateNotice } from '@/api/system/notice';
import addressList from '@/components/CityPicker/cityData.js';

export default {
  props: {
    // 1：按重量 2：按件数
    billingMethod: {
      type: Number,
      default: () => [],
    },
    tableBodyList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      addressList,
      loading: false,
      address: '',
      form: {
        id: '',
        name: '',
        nameCity: [],
        nameArea: [],
        nameAddress: '',
      },
      // 接口存储对象：five step
      interfaceObj: {
        detApiName: getNotice,
        addApiName: addNotice,
        editApiName: updateNotice,
      },
      tableData: {
        tableHeaderList: [
          {
            prop: 'picCanArea',
            label: '可配送区域',
            showMethod: 'string',
          },
          {
            prop: 'first',
            label: '首重（kg）',
            showMethod: 'number',
          },
          // {
          //   prop: "firstPiece",
          //   label: "首件（个）",
          //   showMethod: "number",
          // },
          {
            prop: 'firstFee',
            label: '运费（元）',
            showMethod: 'number',
          },
          {
            prop: 'second',
            label: '续重（kg）',
            showMethod: 'number',
          },
          // {
          //   prop: "secondPiece",
          //   label: "续件（个）",
          //   showMethod: "number",
          // },
          {
            prop: 'secondFee',
            label: '续费（元）',
            showMethod: 'number',
          },
        ],
        tableBodyList: [],
      },
      freightTemplateAreaVo: [],
    };
  },
  created() {
    // tableBodyList拿到之后赋值
    this.tableData.tableBodyList = this.tableBodyList;
  },
  methods: {
    remoteItem(scope) {
      this.tableData.tableBodyList.splice(scope.$index, 1);
      // 扁平化且过滤 区
      const codeArea = this.getAreaData(6);
      this.recursionArea(this.addressList, codeArea);
    },
    handleChange() {
      for (let i = 0; i < this.tableData.tableBodyList.length; i++) {
        const nodes = this.$refs.cascader[i]?.getCheckedNodes();
        // console.log(nodes);
        if (!nodes) return;

        // Initialize freightTemplateAreaVo
        this.freightTemplateAreaVo[i] = {};

        // Initialize sets
        let codeArea = new Set();
        let codeCity = new Set();
        let codeProvince = new Set();
        let nameArea = new Set();
        let nameCity = new Set();
        let nameProvince = new Set();

        // Iterate over checked nodes
        for (let node of nodes) {
          let currentNode = node;

          // Process current node
          switch (currentNode.value.length) {
            case 6:
              codeArea.add(currentNode.value);
              nameArea.add(currentNode.label);
              break;
          }

          // Process parent (city)
          if (currentNode.parent) {
            currentNode = currentNode.parent;
            codeCity.add(currentNode.value);
            nameCity.add(currentNode.label);

            // Process grandparent (province)
            if (currentNode.parent) {
              currentNode = currentNode.parent;
              codeProvince.add(currentNode.value);
              nameProvince.add(currentNode.label);
            }
          }
        }

        // Create data structure
        let data = {
          isDelete: 0,
          codeArea: Array.from(codeArea).join(','),
          codeCity: Array.from(codeCity).join(','),
          codeProvince: Array.from(codeProvince).join(','),
          nameArea: Array.from(nameArea).join(','),
          nameCity: Array.from(nameCity).join(','),
          nameProvince: Array.from(nameProvince).join(','),
          picCanArea: JSON.stringify(
            this.tableData.tableBodyList[i].picCanArea
          ),
          first: this.tableData.tableBodyList[i].first,
          firstFee: this.tableData.tableBodyList[i].firstFee,
          second: this.tableData.tableBodyList[i].second,
          secondFee: this.tableData.tableBodyList[i].secondFee,
        };

        // Add the data structure to freightTemplateAreaVo
        Object.assign(this.freightTemplateAreaVo[i], data);
      }
    },
    // 6位长度的code返回省，4位返回市，2位返回区
    getAreaData(length = 6) {
      // 处理数据
      const picCanAreas = this.tableData.tableBodyList.flatMap(
        (item) => item.picCanArea
      );
      const picCanAreasFlat = picCanAreas.flat().filter((item) => item);
      // 去重
      let deduplicatedData = picCanAreasFlat.reduce(
        (accumulator, currentValue) => {
          if (!accumulator.includes(currentValue)) {
            accumulator.push(currentValue);
          }
          return accumulator;
        },
        []
      );
      deduplicatedData = deduplicatedData.filter(
        (item) => item.length == length
      );
      return deduplicatedData;
    },
    // 递归处理区
    recursionArea(data, disableList) {
      // 如果包含children，递归
      data.forEach((item) => {
        if (disableList.includes(item.code)) {
          this.$set(item, 'disabled', true);
        } else {
          this.$set(item, 'disabled', false);
        }
        if (item.children) {
          this.recursionArea(item.children, disableList);
        }
      });
    },
    // 递归处理市
    recursionCity(data, disableList) {
      // 如果children的disabled为true，则设置disabled为true
      data.forEach((item) => {
        if (item.children?.every((item) => item.disabled)) {
          this.$set(item, 'disabled', true);
        } else {
          this.$set(item, 'disabled', false);
        }
        if (item.children) {
          this.recursionCity(item.children, disableList);
        }
      });
    },
    // 处理省
    recursionProvince(data, disableList) {
      data.forEach((item) => {
        if (item.children.every((item) => item.disabled)) {
          this.$set(item, 'disabled', true);
        } else {
          this.$set(item, 'disabled', false);
        }
      });
    },
    addAddress() {
      this.tableData.tableBodyList.push({
        id: this.tableData.tableBodyList.length,
        picCanArea: '',
        first: '',
        firstFee: '',
        second: '',
        secondFee: '',
      });
      // 扁平化且过滤 区
      const codeArea = this.getAreaData(6);
      this.recursionArea(this.addressList, codeArea);
      
      // // 过滤市
      // const codeCity = this.getAreaData(4);
      // this.recursionCity(this.addressList, codeCity);
      

      // // 过滤省
      // const codeProvince = this.getAreaData(2);
      // this.recursionCity(this.addressList, codeProvince);
    },
    billingMethodComputed() {
      // 1：按重量 2：按件数
      const first = this.tableData.tableHeaderList.find(
        (item) => item.prop === 'first'
      );
      const second = this.tableData.tableHeaderList.find(
        (item) => item.prop === 'second'
      );
      if (this.billingMethod === 1) {
        first.label = '首重（kg）';
        second.label = '续重（kg）';
        return true;
      }
      first.label = '首件（个）';
      second.label = '续件（个）';
    },
    validate() {
      for (let i = 0; i < this.tableData.tableBodyList.length; i++) {
        if (this.tableData.tableBodyList[i].picCanArea.length === 0) {
          this.$message.error('请选择可配送区域');
          return false;
        }
        if (isNaN(this.tableData.tableBodyList[i].first)) {
          this.$message.error('请填写首重');
          return false;
        }
        if (isNaN(this.tableData.tableBodyList[i].firstFee)) {
          this.$message.error('请填写运费');
          return false;
        }
        if (isNaN(this.tableData.tableBodyList[i].second)) {
          this.$message.error('请填写续重');
          return false;
        }
        if (isNaN(this.tableData.tableBodyList[i].secondFee)) {
          this.$message.error('请填写续费');
          return false;
        }
      }
      return true;
    },
  },
  watch: {
    'tableData.tableBodyList': {
      handler(newValue, oldValue) {
        this.handleChange();
      },
      deep: true,
    },
    billingMethod: {
      handler(newValue, oldValue) {
        this.billingMethodComputed();
      },
      deep: true,
    },
  },
};
</script>

<style lang="scss" scoped>
.areaCheckBox {
  width: 100%;
  height: 60vh;
  border: 1px solid #ccc;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;

  .province,
  .city,
  .country {
    overflow-y: auto;
    flex: 1;

    ::v-deep.el-checkbox__label {
      letter-spacing: 1ch !important;
    }
  }

  .city {
    padding: 0 20px;
  }
}

::v-deep.el-checkbox-group {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}
.areaFreight {
  position: relative;
  ::v-deep.el-form-item__label {
    margin-left: 10px;
  }

  &:after {
    position: absolute;
    top: 10px;
    left: 0;
    content: '*';
    color: red;
  }
}
</style>

<style>
.editManage .el-table th.el-table__cell > .cell::before {
  content: '*';
  padding-right: 4px;
  color: red;
}
</style>
